﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace GoodStuff.Heartbeat.Core.Sensors
{
    public class WebRequestSensor : ISensor
    {
        private string _uri;
        private SensorChannel _uriChannel;
        private SensorChannel _durationChannel;

        /// <summary>
        /// Warning: you should set a really low connection-timeout otherwise the sensor might block.
        /// </summary>
        /// <param name="connectionString"></param>
        public WebRequestSensor(string uri)
        {
            _uri = uri;
            _uriChannel = new SensorChannel() { Description = "HTTP Response", Units = "bool", DefaultLow = 0, DefaultHigh = float.MaxValue, Value = 0.0f };
            _durationChannel = new SensorChannel() { Description = "Response time", Units = "msecs", DefaultLow = 0, DefaultHigh = 10000, Value = 0.0f };
        }

        public string Name
        {
            get { return "WebRequest"; }
        }

        public void Update()
        {
            WebRequest request = WebRequest.Create(_uri);
            DateTime now = DateTime.Now;

            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (Stream stream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    reader.ReadToEnd();
                }

                _uriChannel.Value = (response.StatusCode == HttpStatusCode.OK) ? 1 : 0;
                _durationChannel.Value = (float)((DateTime.Now - now).TotalMilliseconds);
            }
        }

        public IEnumerable<ISensorChannel> Values
        {
            get
            {
                yield return _uriChannel;
                yield return _durationChannel; 
            }
        }
    }
}
